package com.shensi.adminCollect.controller.customer;


import com.shensi.adminCollect.common.annotation.Excel;
import com.shensi.common.core.controller.BaseController;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.core.page.TableDataInfo;
import com.shensi.adminCollect.common.enums.ErrorCode;
import com.shensi.adminCollect.common.exception.CustomException;
import com.shensi.adminCollect.common.utils.StringUtils;
import com.shensi.adminCollect.common.utils.poi.ExcelUtil;
import com.shensi.adminCollect.domain.customer.CardExcelImport;
import com.shensi.adminCollect.domain.customer.dto.CardExcelItem;
import com.shensi.adminCollect.domain.customer.dto.CardExcelItemEnter;
import com.shensi.adminCollect.domain.customer.dto.LabelRuleUser;
import com.shensi.adminCollect.domain.customer.dto.LabelRuleUserEnter;
import com.shensi.adminCollect.service.customer.ICardExcelImportService;
import com.shensi.adminCollect.service.customer.ICustomerCardSettingService;
import com.shensi.adminCollect.domain.system.GzhNewsTemplate;
import com.shensi.adminCollect.domain.system.SysAppUserInfoUser;
import com.shensi.adminCollect.domain.system.SysEnterpriseUser;
import com.shensi.adminCollect.domain.system.SysStationUser;
import com.shensi.adminCollect.service.system.IAppUserInfoUserService;
import com.shensi.adminCollect.service.system.IGzhNewsTemplateService;
import com.shensi.adminCollect.service.system.ISysEnterpriseUserService;
import com.shensi.adminCollect.service.system.ISysStationUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.utils.SecurityUtils;
import com.shensi.common.core.domain.entity.SysUser;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

/**
 * 导入excel信息Controller
 *
 * @author qujia
 * @date 2021-05-18
 */
@RestController
@RequestMapping("/customer/cardImport")
public class CardExcelImportController extends BaseController
{

    private static final Logger log = LoggerFactory.getLogger(CardExcelImportController.class);

    @Autowired
    private ICardExcelImportService cardExcelImportService;

    @Autowired
    private IAppUserInfoUserService appUserInfoUserService;

    @Autowired
    private ISysEnterpriseUserService  sysEnterpriseUserService;


    @Autowired
    private IGzhNewsTemplateService gzhNewsTemplateService;
    @Autowired
    private ICustomerCardSettingService customerCardSettingService;
    @Autowired
    private ISysStationUserService stationUserService;




    /**
     *  导入excel的客户信息
     *
     * @param id 客户信息的
     * @return 客户电子会员卡充值消费记录
     */
    @GetMapping(value = "/{id}")
    public AjaxResult selectCardExcelImportById(@PathVariable("id") Long id)
    {
        return AjaxResult.success( cardExcelImportService.selectCardExcelImportById(id));
    }

    /**
     * 查询导入excel信息
     *
     * @param cardExcelImport  条件
     * @return 客户电子会员卡充值消费记录
     */
    @GetMapping("/list")
    public TableDataInfo selectCardExcelImportList(CardExcelImport  cardExcelImport)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        cardExcelImport.setEnterpriseId(loginUser.getUser().getEnterpriseId());
        startPage();
        List<CardExcelImport> recordList = cardExcelImportService.selectCardExcelImportList(cardExcelImport);
        return getDataTable(recordList);
    }

    /**
     * 下载模板
     */

    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<CardExcelImport> util = new ExcelUtil<CardExcelImport>(CardExcelImport.class);
        return util.importTemplateExcel("学生数据");
    }




    /**
     * 导入list信息
     */
    @PostMapping("/importCardExcel")
    @ResponseBody
    public AjaxResult importCardExcel(@RequestBody List<CardExcelImport> cardExcelImports)
    {
        Integer falge=0;
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(!"1".equals(loginUser.getUser().getUserLevel())){
            return AjaxResult.error("非油企用户禁止导入信息");
        }
        for (CardExcelImport cardExcelImport : cardExcelImports) {
            if (cardExcelImport.getGrowValue() == null) {
                cardExcelImport.setGrowValue(0);
            }
            if (cardExcelImport.getIntegral() == null) {
                cardExcelImport.setIntegral(0);
            }
            if (cardExcelImport.getBalance() == null) {
                cardExcelImport.setBalance(BigDecimal.ZERO);
            }
        }

        SysEnterpriseUser enterpriseUser = sysEnterpriseUserService.selectSysEnterpriseUserById(loginUser.getUser().getEnterpriseId());
        SysStationUser stationUser = null;
        String customerCardreflue = enterpriseUser.getCardFlag();

        if(cardExcelImports.size()<=0){
            return AjaxResult.error("导入信息不许为空");
        }
        if(customerCardreflue.equals("0")){
            return AjaxResult.error("油企电子卡未开启");
        }
        if(cardExcelImports.get(0).getSendFalge()!=null&&cardExcelImports.get(0).getSendFalge().equals("1")){
            falge=1;
        }

        Integer stationId = cardExcelImports.get(0).getStationId();
        if (stationId == null) {
            return AjaxResult.error("未选择油站");
        }

        try {
            stationUser = stationUserService.selectSysStationUserById(stationId.longValue());
            if (stationUser == null) {
                throw new CustomException(ErrorCode.STATION_NOT_FOUND);
            }
            String message = importData(cardExcelImports, enterpriseUser, falge,stationUser);
            return AjaxResult.success(message);
            // 处理成功的逻辑
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常堆栈信息

            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            String stackTrace = sw.toString();

            // 处理异常的逻辑
            return AjaxResult.error("处理异常：" + stackTrace);
        }



    }

    @PostMapping("import")
    public AjaxResult importCardExcelData(@RequestParam("file") MultipartFile file) throws Exception {
        return AjaxResult.success(cardExcelImportService.importCardExcelData(file));
    }
    @PostMapping("/importLabelUser/{labelId}")
    public AjaxResult importCardAndLabelUserExcelData(@RequestParam("file") MultipartFile file,@PathVariable("labelId")Long labelId) throws Exception {
        return AjaxResult.success(cardExcelImportService.importCardAndLabelUserExcelData(file,labelId));
    }

    @GetMapping("labelUserTemplate")
    public void downloadLabelUsertemplate(HttpServletResponse response) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        try {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("template.xlsx", "UTF-8"));
            if (StringUtils.equals("admin", user.getUserName())) {
                ExcelUtil<LabelRuleUser> excelUtil = new ExcelUtil<>(LabelRuleUser.class);
                excelUtil.init(Collections.emptyList(),"sheet1", Excel.Type.EXPORT);
                excelUtil.exportExcel(response.getOutputStream());
            } else {
                ExcelUtil<LabelRuleUserEnter> excelUtil = new ExcelUtil<>(LabelRuleUserEnter.class);
                excelUtil.init(Collections.emptyList(),"sheet1", Excel.Type.EXPORT);
                excelUtil.exportExcel(response.getOutputStream());
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    @GetMapping("template")
    public void downloadTemplate(HttpServletResponse response) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        try {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("template.xlsx", "UTF-8"));
            if (StringUtils.equals("admin", user.getUserName())) {
                ExcelUtil<CardExcelItem> excelUtil = new ExcelUtil<>(CardExcelItem.class);
                excelUtil.init(Collections.emptyList(),"sheet1", Excel.Type.EXPORT);
                excelUtil.exportExcel(response.getOutputStream());
            } else {
                ExcelUtil<CardExcelItemEnter> excelUtil = new ExcelUtil<>(CardExcelItemEnter.class);
                excelUtil.init(Collections.emptyList(),"sheet1", Excel.Type.EXPORT);
                excelUtil.exportExcel(response.getOutputStream());
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }


    public String importData(List<CardExcelImport> dataManagementList,SysEnterpriseUser enterpriseUser,Integer sendFlage,SysStationUser stationUser)
    {
        Long enterpriseId = enterpriseUser.getEnterpriseId();
        boolean coupy=false;
        StringBuilder copyMsg = new StringBuilder();
        LoginUser loginUser=SecurityUtils.getLoginUser();
        if (StringUtils.isNull(dataManagementList) || dataManagementList.size() == 0)
        {
            throw new CustomException("导入数据不能为空！");
        }
        Map<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < dataManagementList.size(); i++) {
        String key = dataManagementList.get(i).getPhoneNumber();
        String old = map.get(key);
        if (old != null) {
        map.put(key, old + "," + (i + 1));
        } else {
        map.put(key, "" + (i + 1));
        }
        }

        Iterator<String> it = map.keySet().iterator();

        while (it.hasNext()) {
        String key = it.next();
        String value = map.get(key);
        if (value.indexOf(",") != -1) {
            coupy=true;
        copyMsg.append("<br/>").append(key).append(" 重复,行： ").append(value);
        }
        }
        if(coupy){
            return  copyMsg.toString();
        }



        int successNum = 0;
        int failureNum = 0;
        SysAppUserInfoUser sysAppUserInfoUser=new SysAppUserInfoUser();
        sysAppUserInfoUser.setStationId(enterpriseId);
        List<SysAppUserInfoUser> appUserInfoUsers=appUserInfoUserService.selectAppUserInfoTable(sysAppUserInfoUser);

        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        //查询模板消息和公众号信息
        //SysEnterpriseUser sysEnterprise=sysEnterpriseUserService.selectSysEnterpriseUserById(enterpriseId);
        GzhNewsTemplate gzhNewsTemplate=new GzhNewsTemplate();
        gzhNewsTemplate.setStationId(enterpriseId);
        gzhNewsTemplate.setTemplateType("1");
        List<GzhNewsTemplate> gzhNewsTemplateList=gzhNewsTemplateService.selectGzhNewsTemplateList(gzhNewsTemplate);
        if(gzhNewsTemplateList==null||gzhNewsTemplateList.size()<=0){
            sendFlage=0;
        }


        for (CardExcelImport importData : dataManagementList){
            if (importData.getChangePhone() == null) {
                importData.setChangePhone(Boolean.FALSE);
            }
            if (importData.getChangePhone()) {
                // 替换旧手机号
                if (StringUtils.isBlank(importData.getOldPhoneNumber())) {
                    // 判断旧手机号是不是为空
                    failureNum++;
                    failureMsg.append("<br/>").append(failureNum).append("、账号 ").append(importData.getPhoneNumber()).append(" 导入失败：旧手机号为空");
                    continue;
                }else if(StringUtils.equals(importData.getOldPhoneNumber(),importData.getPhoneNumber())){
                    // 新旧手机号相同，设置false
                    importData.setChangePhone(Boolean.FALSE);
                }
            }
            try {
                if(sendFlage==0){
                    cardExcelImportService.importOne(importData,appUserInfoUsers,sendFlage,enterpriseUser,stationUser,new GzhNewsTemplate());
                }else{
                    cardExcelImportService.importOne(importData,appUserInfoUsers,sendFlage,enterpriseUser,stationUser,gzhNewsTemplateList.get(0));
                }

                successNum++;
                successMsg.append("<br/>").append(successNum).append("、数据 ").append(importData.getPhoneNumber()).append(" 导入成功");

            }catch (Exception e)
            {
                logger.error(e.getMessage(),e);
                importData.setImportStatus("1");
                importData.setEnterpriseId(enterpriseId);
                importData.setCreateBy(loginUser.getUser().getUserId()+"");
                importData.setCreateTime(new Date());
                cardExcelImportService.insertCardExcelImport(importData);
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、账号 ").append(importData.getPhoneNumber()).append(" 导入失败：");
                if( e instanceof CustomException){
                    failureMsg.append(((CustomException) e).getMsg());
                }else{
                    failureMsg.append(e.getMessage());
                }

            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            return failureMsg.toString();
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
    /**
     * 新增导入的信息
     *
     * @param cardExcelImport 新增的excel信息
     * @return 结果
     */
    @PostMapping
    public AjaxResult insertCardExcelImport(CardExcelImport cardExcelImport)
    {
        return toAjax( cardExcelImportService.insertCardExcelImport(cardExcelImport));
    }

    /**
     * 修改导入的excel信息
     *
     * @param cardExcelImport 修改的导入客户信息
     * @return 结果
     */
    @PutMapping
    public AjaxResult updateCardExcelImport(CardExcelImport cardExcelImport)
    {
        return toAjax( cardExcelImportService.updateCardExcelImport(cardExcelImport));
    }

    /**
     * 批量删除客户电子会员卡充值消费记录
     *
     * @param ids 需要删除的客户电子会员卡充值消费记录ID
     * @return 结果
     */
    @DeleteMapping("/{ids}")
    public AjaxResult deleteCardExcelImportByIds(Long[] ids)
    {
        return toAjax( cardExcelImportService.deleteCardExcelImportByIds(ids));
    }




}
